package com.example.demo.server;

import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PathVariable;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @AUTHOR LYF
 * @DATE 2022/2/11
 * @VERSION 1.0
 * @DESC
 */
@Component
@ServerEndpoint("/demo/{userId}")
public class WebSocketServer {
       private static ConcurrentHashMap<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
       private Session session;
       private String userId="";
       @OnOpen
       public void onOpen(Session session,@PathParam("userId") String userId){
            System.out.println("Server Connected User-"+userId);
            this.session = session;
            this.userId = userId;
            if(webSocketMap.containsKey(userId)){
                webSocketMap.remove(userId);
            }
            webSocketMap.put(userId,this);
            System.out.println("Connected:");
            webSocketMap.forEach((param1,param2)->{
                System.out.println(param1);
            });
       }
       @OnClose
       public void onClose(){
            System.out.println("User-"+userId+" exiting..");
            if(webSocketMap.containsKey(userId)){
                webSocketMap.remove(userId);
            }
       }
       @OnMessage
       public void onMessage(String message,Session session){
           System.out.println(session.getId()+":"+message);
       }
       @OnError
       public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }

      /**
       * 实现服务器主动推送
       */
       public void sendMessage(String message) throws IOException {
            this.session.getBasicRemote().sendText(message);
       }

      /**
       * 发送自定义消息
       */
      public static void sendInfo(String message, String userId) throws IOException {
          System.out.println("推送至User-"+userId);
          System.out.println("推送:"+webSocketMap.get(userId));
          WebSocketServer ws = webSocketMap.get(userId);
          if(ws==null){
              // 离线
              System.out.println("User-"+userId+" not online");
              return;
          }
          ws.sendMessage(message);
      }

      public static ConcurrentHashMap<String, WebSocketServer> getWebSocketMap(){
        return webSocketMap;
    }


}
